package com.bungarus.device.model;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 * Device GRPC service component.
 * It is ready, but currently we use rest service instead (refer to DeviceController), so it's not available now
 */
public class DeviceGrpcApplication {
    Logger logger = Logger.getLogger(DeviceGrpcApplication.class);
    private Server server;
    private final static int SERVER_PORT = 9020;

    private DeviceGrpcService grpcService;

    @Autowired
    public DeviceGrpcApplication(DeviceGrpcService grpcService) {
        this.grpcService = grpcService;
    }

    @PostConstruct
    public void init() throws InterruptedException, IOException {
        this.start();
        this.awaitTermination();
    }

    private void start() throws IOException {
        this.server = ServerBuilder.forPort(SERVER_PORT)
                            .addService(grpcService)
                            .build()
                            .start();
        logger.info("server started！");

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("server shutting down ....");
            this.stop();
        }));
    }

    @PreDestroy
    private void stop() {
        if (server != null) {
            this.server.shutdown();
        }
    }

    private void awaitTermination() throws InterruptedException {
        if (this.server != null) {
            this.server.awaitTermination();
        }
    }

}